﻿Shader "RenderingPractice/Blinn-Phong Fragment-Level"//逐片元光照（Blinn-Phong）
{
    Properties
    {
        _Diffuse ("Diffuse", Color) = (1,1,1,1)//漫反射颜色
		_Specular("Specular",Color) = (1,1,1,1)//镜面反射颜色
		_Gloss("Gloss(光泽度)",Range(8.0,256.0)) = 20//光泽度（表面光滑度，影响高光大小）
    }
    SubShader
    {
        Tags { "LightMode"="ForwardBase" }

        Pass
        {
            CGPROGRAM
            #pragma vertex VertexFunction
            #pragma fragment FragmentFunction

            #include "UnityCG.cginc"
            #include "Lighting.cginc"
			
            fixed4 _Diffuse;//漫反射颜色
			fixed4 _Specular;//镜面反射颜色
			float _Gloss;//光泽度（表面光滑度，影响高光大小）

            struct a2v
            {
                float4 vertex : POSITION; 
				float3 normal :NORMAL;//模型空间表面法线
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
				float3 worldNormal : TEXCOORD0;
				float4 worldPos : TEXCOORD1;
            };
			//顶点函数
            v2f VertexFunction (a2v v)
            {
                v2f o;
				//顶点坐标：模型空间=>裁剪空间
                o.vertex = UnityObjectToClipPos(v.vertex);
				o.worldNormal = UnityObjectToWorldNormal(v.normal);
				o.worldPos = mul(unity_ObjectToWorld ,v.vertex );
                return o;
            }
			//片元函数
            fixed4 FragmentFunction (v2f i) : SV_Target
            {
				//1.环境光：
				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
				//2.漫反射：
				fixed3 worldNormalDir = normalize(i.worldNormal);//n
				//fixed3 worldLightDir = normalize(_WorldSpaceLightPos0.xyz);//l
				fixed3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.worldPos.xyz));//l
				fixed3 diffuseColor = _LightColor0.rgb * _Diffuse.rgb * saturate(dot(worldNormalDir ,worldLightDir));
				//3.镜面反射颜色（Blinn-Phong）
				//float3 viewDir = normalize(_WorldSpaceCameraPos.xyz - i.worldPos.xyz);
				float3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos.xyz));
				float3 hDir = normalize(viewDir + worldLightDir);//h
				fixed3 specularColor = _LightColor0.rgb * _Specular.rgb * pow(saturate(dot(worldNormalDir ,hDir)) ,_Gloss);
				//3.光照颜色：
				fixed4 c = fixed4(ambient + diffuseColor + specularColor ,1.0);
                return c;
            }
            ENDCG
        }
    }
	FallBack "Specular"
}